
#include <BOpenGL>
#include <BRender>
#include <BCamera>
#include <BTexture>

#include <BBillboard>
#include "member_BBillboard.h"

using namespace BWE;

#define member					(*(member_BBillboard*)_ptr)
#define member_allocate()		_ptr = new member_BBillboard(this)
#define member_release()		delete (member_BBillboard*)_ptr

BBillboard::BBillboard()
{
	member_allocate();
}
BBillboard::BBillboard(float size)
{
	member_allocate();
	this->setWidth(size);
	this->setHeight(size);
}
BBillboard::BBillboard(float width, float height)
{
	member_allocate();
	this->setWidth(width);
	this->setHeight( height);
}
BBillboard::~BBillboard()
{
	member_release();
}

void BBillboard::setWidth(float width)
{
	if(member.width != width)
	{
		member.width = width;
		this->dirty();
	}
}
void BBillboard::setHeight(float height)
{
	if(member.height != height)
	{
		member.height = height;
		this->dirty();
	}
}

BBox BBillboard::refresh()
{
	float hh = member.height * 0.5f;
	float hw = member.width * 0.5f;
	float radius = sqrt(hh *hh + hw * hw);
	BSpace space;
	space.expand(member.quad.a());
	space.expand(member.quad.b());
	space.expand(member.quad.c());
	space.expand(member.quad.d());
	return space;
}
void BBillboard::render(BRender& render)
{
	BMatrix matrix = this->matrix();
	if (const BNode* node = render.node())
		matrix *= node->matrix();
	matrix.inverse();
	
	const BCamera* camera = render.camera();
	BVector vec = camera->position() * matrix - this->position();
	vec.normalize();
	BQuater quater(BVector(0, 0, 1.0f), vec);
	
	//glBlendFunc(GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GEQUAL, 0.1f);
	member.quad.a() = BVector(-member.width * 0.5f, -member.height * 0.5f, 0);
	member.quad.b() = BVector(member.width * 0.5f, -member.height * 0.5f, 0);
	member.quad.c() = BVector(member.width * 0.5f, member.height * 0.5f, 0);
	member.quad.d() = BVector(-member.width * 0.5f, member.height * 0.5f, 0);

	member.quad.a() *= quater;
	member.quad.b() *= quater;
	member.quad.c() *= quater;
	member.quad.d() *= quater;

	render.fillQuad(member.quad);
	this->dirty();

	//render.setTexture(0);
	//render.setLighting(false);
	//render.setColor(255, 0, 0);
	//render.drawBox(this->box());
	//render.setColor(0, 0, 255);
	//render.drawQuad(member.quad);
}

